package com.cxhc.system.service.cockpit.impl;

import com.cxhc.common.annotation.Integral;
import com.cxhc.common.core.domain.model.LoginUser;
import com.cxhc.common.enums.IntegralType;
import com.cxhc.common.enums.RepairType;
import com.cxhc.common.utils.DateUtils;
import com.cxhc.common.utils.SecurityUtils;
import com.cxhc.common.utils.StringUtils;
import com.cxhc.system.domain.app.IntegralRecords;
import com.cxhc.system.domain.cockpit.RpFeedback;
import com.cxhc.system.domain.cockpit.RpFeedbackFlow;
import com.cxhc.system.mapper.cockpit.RpFeedbackFlowMapper;
import com.cxhc.system.mapper.cockpit.RpFeedbackMapper;
import com.cxhc.system.service.app.IIntegralRecordsService;
import com.cxhc.system.service.cockpit.IRpFeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RpFeedbackServiceImpl implements IRpFeedbackService {

    @Autowired
    private RpFeedbackMapper rpFeedbackMapper;

    @Autowired
    private RpFeedbackFlowMapper rpFeedbackFlowMapper;

    @Resource
    private IIntegralRecordsService integralRecordsService;

    /**
     * 查询报修
     *
     * @param ID 报修主键
     * @return 报修
     */
    @Override
    public RpFeedback selectRpFeedbackByID(Long ID)
    {
        RpFeedback rpFeedback = rpFeedbackMapper.selectRpFeedbackByID(ID);

        rpFeedback.setRpFeedbackFlows(rpFeedbackFlowMapper.selectRpFeedbackFlowByFeedbackID(ID));
        if(!StringUtils.isEmpty(rpFeedback.getPubPhoto())){
            rpFeedback.setPubPhoto(rpFeedback.getPubPhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
        }
        if (!StringUtils.isEmpty(rpFeedback.getCompletePhoto())){
            rpFeedback.setCompletePhoto(rpFeedback.getCompletePhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
        }
        return rpFeedback;
    }

    /**
     * 查询报修
     *
     * @param ID 报修主键
     * @return 报修
     */
    @Override
    public RpFeedback selectRpFeedbackByIDForApp(Long ID)
    {
        RpFeedback rpFeedback = rpFeedbackMapper.selectRpFeedbackByID(ID);

        rpFeedback.setRpFeedbackFlows(rpFeedbackFlowMapper.selectRpFeedbackFlowByFeedbackIDForApp(ID));
        if(!StringUtils.isEmpty(rpFeedback.getPubPhoto())){
            rpFeedback.setPubPhoto(rpFeedback.getPubPhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
        }
        if (!StringUtils.isEmpty(rpFeedback.getCompletePhoto())){
            rpFeedback.setCompletePhoto(rpFeedback.getCompletePhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
        }
        return rpFeedback;
    }

    /**
     * 查询报修列表
     *
     * @param rpFeedback 报修
     * @return 报修
     */
    @Override
    public List<RpFeedback> selectRpFeedbackList(RpFeedback rpFeedback)
    {
//        如登录用户不为指挥中心 增加赛选条件
        if (!(44601L == SecurityUtils.getUserId())){
            rpFeedback.setAcceptEntId(String.valueOf(SecurityUtils.getUserEntId()));
            rpFeedback.setEntId(SecurityUtils.getUserEntId());
        }
        List<RpFeedback> rpFeedbacks = rpFeedbackMapper.selectRpFeedbackList(rpFeedback);

        for (RpFeedback feedback : rpFeedbacks) {
            if (!StringUtils.isEmpty(feedback.getPubPhoto())){
                feedback.setPubPhoto(feedback.getPubPhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
            }
            if (!StringUtils.isEmpty(feedback.getCompletePhoto())){
                feedback.setCompletePhoto(feedback.getCompletePhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
            }
        }
        return rpFeedbacks;
    }

    @Override
    public List<RpFeedback> selectRpFeedbackListForCockpit(RpFeedback rpFeedback) {
        List<RpFeedback> rpFeedbacks = rpFeedbackMapper.selectRpFeedbackList(rpFeedback);

        for (RpFeedback feedback : rpFeedbacks) {
            if (!StringUtils.isEmpty(feedback.getPubPhoto())){
                feedback.setPubPhoto(feedback.getPubPhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
            }
            if (!StringUtils.isEmpty(feedback.getCompletePhoto())){
                feedback.setCompletePhoto(feedback.getCompletePhoto().replaceAll("http://img.wq-info.com","https://huanchuang-imgs.wq-info.com"));
            }
        }
        return rpFeedbacks;
    }

    private boolean check(Long feedbackId){
        RpFeedbackFlow rpFeedbackFlow = rpFeedbackFlowMapper.selectRpFeedbackFlowByFeedbackIDAndStatus(feedbackId);
        return !ObjectUtils.isEmpty(rpFeedbackFlow);
    }

    @Override
    public int transfer(RpFeedbackFlow rpFeedbackFlow) {
        Long feedbackId = rpFeedbackFlow.getFeedbackId();
        RpFeedback rpFeedback = rpFeedbackMapper.selectRpFeedbackByID(feedbackId);
        if (!(rpFeedback.getStatus() == 1L && ObjectUtils.isEmpty(rpFeedback.getAcceptEntId()))){
            throw new RuntimeException("流程状态不是发布不可流转!");
        }
        rpFeedbackFlow.setAppointEntRealName(SecurityUtils.getUseRealName());
        rpFeedbackFlow.setAppointEntName(SecurityUtils.getUserEntName());
        rpFeedbackFlow.setAddTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setStatus(1L);
        rpFeedback.setUpdateTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setAcceptEntId(rpFeedbackFlow.getEntId());
        rpFeedback.setAcceptEntName(rpFeedbackFlow.getEntName());
        rpFeedback.setAppointEntUserId(SecurityUtils.getUserId());
        rpFeedback.setAppointEntTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setAppointEntRealName(rpFeedbackFlow.getAppointEntRealName());
        rpFeedback.setAppointEntEntName(rpFeedbackFlow.getAppointEntName());
        rpFeedback.setAppointDescription(rpFeedbackFlow.getDescription());
        rpFeedbackMapper.updateRpFeedback(rpFeedback);
        return rpFeedbackFlowMapper.insertRpFeedbackFlow(rpFeedbackFlow);
    }

    @Override
    public int back(RpFeedbackFlow rpFeedbackFlow) {
        Long feedbackId = rpFeedbackFlow.getFeedbackId();
        RpFeedback rpFeedback = rpFeedbackMapper.selectRpFeedbackByID(feedbackId);
        if (!(rpFeedback.getStatus() == 1L && !ObjectUtils.isEmpty(rpFeedback.getAcceptEntId()))){
            throw new RuntimeException("流程状态不是流转不可退回!");
        }
        rpFeedback.setStatus(1L);
        rpFeedback.setUpdateTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setBackDescription(rpFeedbackFlow.getDescription());
        rpFeedback.setBackUserId(SecurityUtils.getUserId());
        rpFeedback.setBackUserName(SecurityUtils.getUseRealName());
        rpFeedback.setBackEntId(SecurityUtils.getUserEntId());
        rpFeedback.setBackEntName(SecurityUtils.getUserEntName());
        rpFeedbackMapper.updateRpFeedbackForBack(rpFeedback);
        rpFeedbackFlow.setStatus(3L);
        rpFeedbackFlow.setUserId(SecurityUtils.getUserId());
        rpFeedbackFlow.setRealName(SecurityUtils.getUseRealName());
        rpFeedbackFlow.setEntName(SecurityUtils.getUserEntName());
        rpFeedbackFlow.setEntId(String.valueOf(SecurityUtils.getUserEntId()));
        rpFeedbackFlow.setAddTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        return rpFeedbackFlowMapper.insertRpFeedbackFlow(rpFeedbackFlow);
    }

    @Override
    public int acceptance(RpFeedbackFlow rpFeedbackFlow) {

        Long feedbackId = rpFeedbackFlow.getFeedbackId();
        RpFeedback rpFeedback = rpFeedbackMapper.selectRpFeedbackByID(feedbackId);
        if (!(rpFeedback.getStatus() == 1L && !ObjectUtils.isEmpty(rpFeedback.getAcceptEntId()))){
            throw new RuntimeException("事件不为流转状态或事件已经受理!");
        }
        rpFeedback.setStatus(2L);
        rpFeedback.setUpdateTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setAcceptUserId(SecurityUtils.getUserId());
        rpFeedback.setAcceptRealName(SecurityUtils.getUseRealName());
        rpFeedback.setAcceptTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setUpdateUserId(SecurityUtils.getUserId());
        rpFeedbackMapper.updateRpFeedback(rpFeedback);
        rpFeedbackFlow.setStatus(4L);
        rpFeedbackFlow.setUserId(SecurityUtils.getUserId());
        rpFeedbackFlow.setRealName(SecurityUtils.getUseRealName());
        rpFeedbackFlow.setEntName(SecurityUtils.getUserEntName());
        rpFeedbackFlow.setEntId(String.valueOf(SecurityUtils.getUserEntId()));
        rpFeedbackFlow.setAddTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        return rpFeedbackFlowMapper.insertRpFeedbackFlow(rpFeedbackFlow);
    }

    @Override
    @Integral(IntegralType.HANDLING_EVENTS)
    public int over(RpFeedbackFlow rpFeedbackFlow) {

        Long feedbackId = rpFeedbackFlow.getFeedbackId();
        RpFeedback rpFeedback = rpFeedbackMapper.selectRpFeedbackByID(feedbackId);
        if (!(rpFeedback.getStatus() == 2L && !ObjectUtils.isEmpty(rpFeedback.getAcceptUserId()))){
            throw new RuntimeException("事件未受理不可完修!");
        }
        rpFeedback.setStatus(3L);
        rpFeedback.setUpdateTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));

        rpFeedback.setCompleteUserId(SecurityUtils.getUserId());
        rpFeedback.setCompleteTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        rpFeedback.setCompletePhoto(rpFeedbackFlow.getPhoto());
        rpFeedback.setCompleteEntName(SecurityUtils.getUserEntName());
        rpFeedback.setCompleteRealName(SecurityUtils.getUseRealName());
        rpFeedbackMapper.updateRpFeedback(rpFeedback);
        rpFeedbackFlow.setStatus(2L);
        rpFeedbackFlow.setUserId(SecurityUtils.getUserId());
        rpFeedbackFlow.setEntId(String.valueOf(SecurityUtils.getUserEntId()));
        rpFeedbackFlow.setEntName(SecurityUtils.getUserEntName());
        rpFeedbackFlow.setRealName(SecurityUtils.getUseRealName());
        rpFeedbackFlow.setAddTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        return rpFeedbackFlowMapper.insertRpFeedbackFlow(rpFeedbackFlow);
    }

    /**
     * 新增报修
     *
     * @param rpFeedback 报修
     * @return 结果
     */
    @Override
    public int insertRpFeedback(RpFeedback rpFeedback)
    {
        rpFeedback.setUserId(SecurityUtils.loginUserId());
        rpFeedback.setEntId(SecurityUtils.getUserEntId());
        rpFeedback.setPubEntName(SecurityUtils.getUserEntName());
        rpFeedback.setPubRealName(SecurityUtils.getUseRealName());
        rpFeedback.setStatus(1L);
        int i = rpFeedbackMapper.insertRpFeedback(rpFeedback);
        try {
            insertIntegralRecords(rpFeedback.getRepairType(),rpFeedback.getDescription());

        }catch (Exception e){
            //没事
        }
        return i;
    }

    private void insertIntegralRecords(String repairType,String desc){

        RepairType repairTypeEnum = RepairType.byType(repairType);
        IntegralRecords integralRecords = new IntegralRecords();
        integralRecords.setUserId(SecurityUtils.getUserId());
        integralRecords.setCompanyName(SecurityUtils.getUserEntName());
        integralRecords.setUserName(SecurityUtils.getUseRealName());
        //操作积分
        integralRecords.setIntegral(repairTypeEnum.getIntegral());
        Long balance = SecurityUtils.getUserIntegral();
        integralRecords.setBalance(balance);
        integralRecords.setStatus(1);
        integralRecords.setContent(desc);
        integralRecordsService.insertIntegralRecords(integralRecords);
    }

    /**
     * 修改报修
     *
     * @param rpFeedback 报修
     * @return 结果
     */
    @Override
    public int updateRpFeedback(RpFeedback rpFeedback)
    {
        return rpFeedbackMapper.updateRpFeedback(rpFeedback);
    }

    /**
     * 批量删除报修
     *
     * @param IDs 需要删除的报修主键
     * @return 结果
     */
    @Override
    public int deleteRpFeedbackByIDs(Long[] IDs)
    {
        return rpFeedbackMapper.deleteRpFeedbackByIDs(IDs);
    }

    /**
     * 删除报修信息
     *
     * @param ID 报修主键
     * @return 结果
     */
    @Override
    public int deleteRpFeedbackByID(Long ID)
    {
        return rpFeedbackMapper.deleteRpFeedbackByID(ID);
    }

    @Override
    public Map<String, String> selectEventNum(String startTime,String endTime,String month) {
        return rpFeedbackMapper.queryEventNum(startTime,endTime,month);
    }

    @Override
    public Map<String,Map<String,Object>> eventNumForWeek(String isAlong) {

        Map<String, Map<String, Object>> completeCountMap = rpFeedbackMapper.eventNumForWeek(isAlong, "1");
        Map<String, Map<String, Object>> countMap = rpFeedbackMapper.eventNumForWeek(isAlong,null);
        for (Map.Entry<String, Map<String, Object>> stringMapEntry : countMap.entrySet()) {
            String key = stringMapEntry.getKey();
            Map<String, Object> map = completeCountMap.get(key);
            if (!CollectionUtils.isEmpty(map)){
                Long count = (Long) map.get("count");
                if (!ObjectUtils.isEmpty(count)){
                    stringMapEntry.getValue().put("completeCount",count);
                }else {
                    stringMapEntry.getValue().put("completeCount",0);
                }
            }

        }
        return countMap;
    }

    @Override
    public List<Map<String, Object>> eventNumForUser(String isAlong, String status) {
        rpFeedbackMapper.eventNumForUser(isAlong, status);

        return null;
    }

    @Override
    public Map<String, String> eventNumByAcceptEntID(String startTime, String endTime, String isOver) {

        Map<String, String> mapRes = new HashMap<>();
        List<Map<String, Object>> maps = rpFeedbackMapper.eventNumByAcceptEntID(startTime,endTime,isOver);
        for (Map<String, Object> map : maps) {
            BigDecimal count = new BigDecimal(String.valueOf(map.get("count")));
            String entName = (String) map.get("entName");
            if (StringUtils.isEmpty(entName)) {
                entName = "其他";
            }
            if (BigDecimal.ZERO.equals(count)) {
                mapRes.put(entName, "0");
            } else {
                mapRes.put(entName, count.toString());
            }
        }
        return mapRes;
    }

    @Override
    public Map<String, String> eventNumByEntID(String startTime, String endTime) {
        Map<String, String> mapRes = new HashMap<>();
        List<Map<String, Object>> maps = rpFeedbackMapper.eventNumByEntID(startTime,endTime);
        for (Map<String, Object> map : maps) {
            BigDecimal count = new BigDecimal(String.valueOf(map.get("count")));
            String pubEntName = (String) map.get("pubEntName");
            if (StringUtils.isEmpty(pubEntName)) {
                pubEntName = "其他";
            }
            if (BigDecimal.ZERO.equals(count)) {
                mapRes.put(pubEntName, "0");
            } else {
                mapRes.put(pubEntName, count.toString());
            }
        }
        return mapRes;
    }

    @Override
    public Map<String, String> eventNumByRepairType(String startTime, String endTime) {
        Map<String, String> mapRes = new HashMap<>();
        List<Map<String, Object>> maps = rpFeedbackMapper.eventNumByRepairType(startTime,endTime);
        for (Map<String, Object> map : maps) {
            BigDecimal count = new BigDecimal(String.valueOf(map.get("count")));
            String repairType = (String) map.get("repairType");
            if (StringUtils.isEmpty(repairType)) {
                repairType = "其他";
            }
            if (BigDecimal.ZERO.equals(count)) {
                mapRes.put(repairType, "0");
            } else {
                mapRes.put(repairType, count.toString());
            }
        }
        return mapRes;
    }
}
